package com.eeepay.eeepay_v2.activity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.MerchantQueryAdapter;
import com.eeepay.eeepay_v2.adapter.TradeResultAdapter;
import com.eeepay.eeepay_v2.model.MerchantInfo;
import com.eeepay.eeepay_v2.model.MerchantQueryCri;
import com.eeepay.eeepay_v2.model.QueryResult;
import com.eeepay.eeepay_v2.model.TradeQueryCri;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshListView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.HorizontalItemView;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerchantSuperSearch;
import cn.eeepay.api.grpc.nano.MerchantSuperSearchServiceGrpc;
import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/8 0008.
 * 查询结果界面（商户超级查询 和 交易超级查询 的结果展示）
 */
public class QueryResultActivity extends ABBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private PullToRefreshListView listView;
    private TitleBar titleBar;
//    private RelativeLayout rl_sort;
//    private TextView tv_sort;//排序
    private PopupWindow sortPopWindow;

    private TradeResultAdapter tradeAdapter;
    private MerchantQueryAdapter merchantAdapter;

    private String intentFlag;//界面跳转标志

    private int currPage = 1;
    private int pageSize = 10;
    private int total = 0;
    private String order = "0";//排序

    //商户超级查询条件
    private MerchantQueryCri merchantQueryCri;
    //交易超级查询条件
    private TradeQueryCri tradeQueryCri;

    private HorizontalItemView hv_collect;//add zhuangzqin 2017年4月19日09:57:51 查询汇总样式修改

    @Override
    protected int getLayoutId() {
        return R.layout.activity_query_result;
    }

    @Override
    protected void initWidget() {

        titleBar = getViewById(R.id.title_bar);
        titleBar.setShowRight(View.VISIBLE);
        titleBar.setRightTextView("排序");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

//        rl_sort = getViewById(rl_sort);
//        tv_sort = getViewById(R.id.tv_sort);
        listView = getViewById(R.id.lv_result);
        hv_collect = getViewById(R.id.hv_collect);
        hv_collect.setRootBackColor(R.color.unify_grounding_gray);
        if (bundle != null) {
            intentFlag = bundle.getString(Constant.INTENT_FLAG);
        }

        if (Constant.MERCHANT_QUERY.equals(intentFlag)) {//商户超级查询
            titleBar.setTiteTextView("查询结果");
            titleBar.setShowRight(View.GONE);
//            rl_sort.setVisibility(View.GONE);//商户超级查询暂不做排序
            merchantQueryCri = (MerchantQueryCri) bundle.getSerializable(Constant.MERCHANT_QUERY_CRI);

        } else if (Constant.TRADE_QUERY.equals(intentFlag)) {// 交易超级查询
            titleBar.setTiteTextView("交易超级查询");
            tradeQueryCri = (TradeQueryCri) bundle.getSerializable(Constant.TRADE_QUERY_CRI);

        }
        sendHttpRequest(0);

    }

    @Override
    protected void eventOnClick() {
        //汇总
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                showSortPopWindow(view);
//                if (Constant.MERCHANT_QUERY.equals(intentFlag)) {
//                    goActivity(MerchantCollectActivity.class, bundle);
//                } else if (Constant.TRADE_QUERY.equals(intentFlag)) {
//                    goActivity(TradeCollectActivity.class, bundle);
//                }
            }
        });
        hv_collect.setOnClickListener(this);

        if (Constant.TRADE_QUERY.equals(intentFlag)) {
            tradeAdapter = new TradeResultAdapter(this);
            listView.setAdapter(tradeAdapter);
        } else if (Constant.MERCHANT_QUERY.equals(intentFlag)) {
            merchantAdapter = new MerchantQueryAdapter(this);
            listView.setAdapter(merchantAdapter);
        }

        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnItemClickListener(this);

        //上下拉
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                currPage = 1;
                sendHttpRequest(0);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(total > currPage * pageSize){
                    currPage++;
                    sendHttpRequest(0);
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SystemClock.sleep(1000);
                            showToast("已经是最后一页了");
                            if(listView.isRefreshing()){
                                listView.onRefreshComplete();
                            }
                        }
                    });
                }
            }
        });

    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                if (Constant.MERCHANT_QUERY.equals(intentFlag)) {//商户超级查询
                    MerchantSuperSearch.MerchantSuperSearchRequest request = new MerchantSuperSearch
                            .MerchantSuperSearchRequest();
                    request.agentNode = merchantQueryCri.getAgentNode();
                    request.mobilephone = merchantQueryCri.getPhone();
//                    request.agentNameNo = merchantQueryCri.getAgentName();
                    request.includeSon = "1";
                    request.bpId = merchantQueryCri.getDeviceName();
                    request.mobilephone = merchantQueryCri.getPhone();
                    request.includeSon = "1";
                    request.tranTimeStar = merchantQueryCri.getTradeStartTime();
                    request.tranTimeEnd = merchantQueryCri.getTradeEndTime();
                    request.tranAmountStar = merchantQueryCri.getTradeMinMoney();
                    request.tranAmountEnd = merchantQueryCri.getTradeMaxMoney();
                    if(!TextUtils.isEmpty(merchantQueryCri.getTradeMinCount())){
                        request.tranCountStar = merchantQueryCri.getTradeMinCount();
                    }
                    if(!TextUtils.isEmpty(merchantQueryCri.getTradeMaxCount())){
                        request.tranCountEnd = merchantQueryCri.getTradeMaxCount();
                    }
                    request.province = merchantQueryCri.getProvince();
                    request.city = merchantQueryCri.getCity();
                    request.district = merchantQueryCri.getDistrict();
                    request.pdbStartDate = merchantQueryCri.getIntoStartTime();
                    request.pdbEndDate = merchantQueryCri.getIntoEndTime();
                    request.merchantStatus = merchantQueryCri.getMerchantStatus();
                    request.noBpId = merchantQueryCri.getNoOpenDevice();
                    request.page = currPage;
                    request.size = pageSize;
                    MerchantSuperSearchServiceGrpc.MerchantSuperSearchServiceBlockingStub stub =
                            MerchantSuperSearchServiceGrpc.newBlockingStub(channel)
                            .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                    MerchantSuperSearch.MerchantSuperSearchResponse response = stub.merchantSuperSearchList(request);
                    return response;
                } else if (Constant.TRADE_QUERY.equals(intentFlag)) {// 交易超级查询
                    TransProto.TransBySupperReq request = new TransProto.TransBySupperReq();
                    request.agentNode = tradeQueryCri.getAgentNode();
                    request.agentNameOrNo = tradeQueryCri.getAgentName();
                    request.transBeginTime = tradeQueryCri.getTradeStartTime();
                    request.transEndTime = tradeQueryCri.getTradeEndTime();
                    request.transBeginAmount = tradeQueryCri.getTradeMinMoney();
                    request.transEndAmount = tradeQueryCri.getTradeMaxMoney();
                    request.cardType = tradeQueryCri.getCardType();
                    request.transCardNo = tradeQueryCri.getCardNum();
                    request.merPhone = tradeQueryCri.getPhone();
                    request.merNameOrNo = tradeQueryCri.getMerchantName();
                    request.posType = tradeQueryCri.getDeviceName();
                    request.transStatus = tradeQueryCri.getTradeStatus();
                    request.isInclude = "1";
                    if(TextUtils.isEmpty(tradeQueryCri.getTime())){
                        request.registerBeginTime = tradeQueryCri.getIntoStartTime();
                        request.registerEndTime = tradeQueryCri.getIntoEndTime();
                    }else {
                        request.time = tradeQueryCri.getTime();
                    }
                    request.pageNo = currPage;
                    request.pageSize = pageSize;
                    request.order = order;
                    TransApiServiceGrpc.TransApiServiceBlockingStub stub = TransApiServiceGrpc
                            .newBlockingStub(channel)
                            .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                    return stub.queryTransBySupper(request);

                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                if(listView.isRefreshing()){
                   listView.onRefreshComplete();
                }
                dismissProgressDialog();
                dismissPop();
                if (result == null) {
                    return;
                }
                if (Constant.MERCHANT_QUERY.equals(intentFlag)) {//商户超级查询
                    MerchantSuperSearch.MerchantSuperSearchResponse response = (MerchantSuperSearch.MerchantSuperSearchResponse) result;
                    if(!response.success){
                        showToast(response.msg);
                        return;
                    }
                    MerchantSuperSearch.MerchantSuperInfoSear[] merchantInfos = response.merchantInfo;
                    List<MerchantInfo> merchantList = new ArrayList<>();
                    for (int i = 0; i < merchantInfos.length; i++){
                        MerchantInfo merchantInfo = new MerchantInfo();
                        merchantInfo.setName(merchantInfos[i].merchantName);
                        merchantInfo.setNo(merchantInfos[i].merchantNo);
                        merchantInfo.setPhone(merchantInfos[i].mobilephone);
                        merchantInfo.setState(merchantInfos[i].status);
                        merchantList.add(merchantInfo);
                    }
                    total = response.total;
                    if(currPage == 1){
                        merchantAdapter.setList(merchantList);
                    }else {
                        merchantAdapter.addAll(merchantList);
                    }
                } else if (Constant.TRADE_QUERY.equals(intentFlag)) {// 交易超级查询
                    LogUtils.d("TAG", result.toString());
                    TransProto.TransBySupperRes response = (TransProto.TransBySupperRes) result;
                    if(!response.resMsg.status){
                        showToast(response.resMsg.msg);
                        return;
                    }
                    List<QueryResult> datas = new ArrayList<>();
                    TransProto.TransInfo[] transInfo = response.transInfo;
                    for(int i = 0; i < transInfo.length; i++){
                        QueryResult queryResult = new QueryResult();
                        queryResult.setOrderNumber(transInfo[i].orderNo);
                        queryResult.setTradeTime(transInfo[i].transTime);
                        queryResult.setName(transInfo[i].merchantName);
                        queryResult.setServiceName(transInfo[i].serviceName);
                        queryResult.setSum(transInfo[i].transAmount);
                        queryResult.setDevice(transInfo[i].posTypeName);
                        queryResult.setState(transInfo[i].transStatus);
                        datas.add(queryResult);
                    }
                    if(currPage == 1){
                        tradeAdapter.setList(datas);
                    }else {
                        tradeAdapter.addAll(datas);
                    }
                    total = response.total;

                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hv_collect://汇总查看
//                showSortPopWindow(v);
                if (Constant.MERCHANT_QUERY.equals(intentFlag)) {
                    goActivity(MerchantCollectActivity.class, bundle);
                } else if (Constant.TRADE_QUERY.equals(intentFlag)) {
                    goActivity(TradeCollectActivity.class, bundle);
                }
                break;
            case R.id.view_id://点击灰色区域
                dismissPop();
                break;
        }
    }

    /**
     * 排序
     * @param view
     */
    private void showSortPopWindow(View view) {
        if (view.isSelected()) {
            view.setSelected(false);
        } else {
            view.setSelected(true);
        }
        if (sortPopWindow == null) {
            sortPopWindow = new PopupWindow(mContext);
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_sort_view, null);
            contentView.findViewById(R.id.view_id).setOnClickListener(this);
            ListView lv = (ListView) contentView.findViewById(R.id.listView);
            lv.setAdapter(new ArrayAdapter<>(mContext, R.layout.item_simple_list_1
                    , new String[]{"交易时间降序","交易时间升序","交易金额降序","交易金额升序"}));
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    order = position + "";
                    sendHttpRequest(0);
                }
            });
            sortPopWindow.setContentView(contentView);
            sortPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            sortPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            sortPopWindow.setAnimationStyle(R.style.popwin_top_anim_style);
            //菜单背景色
            ColorDrawable dw = new ColorDrawable(Constant.GRAY_LUCENCY_COLOR);
            sortPopWindow.setBackgroundDrawable(dw);
        }
        if (!sortPopWindow.isShowing()) {
            sortPopWindow.showAsDropDown(getViewById(R.id.view_line));
        } else {
            sortPopWindow.dismiss();
        }

    }

    private void dismissPop(){
        if(sortPopWindow == null || !sortPopWindow.isShowing()){
            return;
        }
//        tv_sort.setSelected(false);
        sortPopWindow.dismiss();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        if (Constant.MERCHANT_QUERY.equals(intentFlag)) {//商户超级查询
            bundle.putString(Constant.MERCHANT_NO, merchantAdapter.getDatas().get(position - 1).getNo());
            goActivity(MerchantDetailsActivity.class, bundle);
        } else if (Constant.TRADE_QUERY.equals(intentFlag)) {// 交易超级查询
            String orderNo = tradeAdapter.getDatas().get(position - 1).getOrderNumber();
            LogUtils.d("TAG", "orderNo1 = " + orderNo);
            bundle.putString(Constant.TRADE_QUERY, orderNo);
            goActivity(TradeDetailsActivity.class, bundle);
        }
    }

}
